package jman.service;

import java.sql.SQLException;
import java.util.List;

import jman.dao.UserDao;
import jman.dao.VoteDao;
import jman.dao.Vote_User1Dao;
import jman.dao.Vote_User2Dao;
import jman.mode.User;
import jman.mode.Vote;

public class UserService {
	public boolean login(int id,String pwd) throws SQLException{
		boolean flag=false;
		UserDao ud=new UserDao();
		if(id!=0&&pwd!=""){
			if(pwd.equals(ud.getUserById(id).getPwd())){
				flag=true;
			}
		}
		return flag;
	}
	public boolean regist(String name,String pwd,String role){
		boolean flag=false;
		User user=new User(name,pwd,role);
		UserDao ud=new UserDao();
		if(name!=""&&pwd!=""&&role!=null){
		flag=ud.addUser(user);
		}
		return flag;
	}
	public int tellIdToUser(String name,String pwd,String role) throws SQLException{
		int id=0;
		UserDao ud=new UserDao();
		User user=ud.getUserWhenRegist(name, pwd, role);
		id=user.getId();
		return id;
	}
	public String getRole(int id) throws SQLException{
		UserDao ud=new UserDao();
		String role=ud.getUserById(id).getRole();
		return role;
	}
	public String getName(int id) throws SQLException{
		UserDao ud=new UserDao();
		String name=ud.getNameById(id);
		return name;
	}
	public List<User> getAllUser() throws SQLException{
		UserDao ud=new UserDao();
		List<User> userList=ud.getUserListAll();
		return userList;
	}
	public List<User> getAllStudents() throws SQLException{
		UserDao ud=new UserDao();
		List<User> userList=ud.getStudentsListAll();
		return userList;
	}
	public List<User> getVotedStudents(int vote_Id) throws SQLException{
		UserDao ud=new UserDao();
		List<User> userList=ud.getUserListByVote_Id(vote_Id);
		return userList;
	}
	public boolean createVote(int raise_UserId,String title,String[] idList1,String[] idList2) throws SQLException{
		boolean flag=false;
		VoteDao vd=new VoteDao();
		Vote_User1Dao vu1d=new Vote_User1Dao();
		Vote_User2Dao vu2d=new Vote_User2Dao();
		if(raise_UserId!=0&&title!=""&&idList1!=null&&idList2!=null){
			Vote vote=new Vote(raise_UserId,"未完成","未完成",title);
			boolean b1=vd.addVote(vote);
			if(b1){
				int id=vd.getId(vote);
				for(String s:idList1){
					int i=Integer.valueOf(s);
					vu1d.add(id, i,0);
				}
				for(String s:idList2){
					int i=Integer.valueOf(s);
					vu2d.add(id, i,"否");
				}
				flag=true;
			}
		}
		return flag;
	}
	public boolean vote(int id,int vote_Id,int user_Id) throws SQLException{
		boolean flag=false;
		UserDao ud=new UserDao();
		VoteDao vd=new VoteDao();
		Vote_User1Dao vu1d=new Vote_User1Dao();
		Vote_User2Dao vu2d=new Vote_User2Dao();
		if(vu2d.isVote(id, vote_Id)){
			vu2d.update(id, vote_Id);
			vu1d.update(vote_Id, user_Id);
			if(vu2d.isFinish(vote_Id)){
				int userId=vu1d.getUser_IdFinally(vote_Id);
				String name=ud.getNameById(userId);
				vd.update(vote_Id, name);
			}
			flag=true;
		}
		return flag;
	}
	public boolean cancelVote(int vote_Id){
		boolean flag=false;
		VoteDao vd=new VoteDao();
		flag=vd.delete(vote_Id);
		return flag;
	}
}
